package org.example.testcode.controller.admin;

import com.alibaba.fastjson.JSON;
import org.example.testcode.bean.TopicEsInfo;
import org.example.testcode.dto.UpdateTopicDTO;
import org.example.testcode.helper.EsTemplate;
import org.example.testcode.helper.TopicHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@RequestMapping("/base")
@RestController
public class TopicBaseAdminController {


    @Autowired
    EsTemplate esTemplate;

    public static final String topicIndex = "techtopic";
    public static final String DomainAccessKey = "www.guoxiongfei.cn";


    /**
     * 前端按ID查询
     *
     * @param id
     * @return
     * @throws IOException
     */
    @GetMapping("/get")
    public String getById(String id, String domain) throws IOException {
        if (null == domain || !DomainAccessKey.equals(domain)) {
            return null;
        }
        if (!(null != id && id.length() > 0)) {
            return null;
        }
        Object object = esTemplate.getDocument(topicIndex, TopicEsInfo.class.getTypeName(), id);
        TopicEsInfo es = JSON.parseObject(JSON.toJSONString(object), TopicEsInfo.class);
        {
            if (null != es.getBodyText() && es.getBodyText().length() > 0) {

            } else {
                TopicEsInfo cnBlogByLink = TopicHelper.getCNBlogByLink(es.getLink());
                if (null == cnBlogByLink) {
                    System.out.println("获取内容失败：" + es.getLink());

                } else {
                    es.setBodyText(cnBlogByLink.getBodyText());
                    if (null != cnBlogByLink.getBodyText() && cnBlogByLink.getBodyText().length() > 0) {
                        es.setNavText(getNavTxt(cnBlogByLink.getBodyText()));
                    }
                    es.setPicUrl(cnBlogByLink.getPicUrl());
                    es.setPicUrl2(cnBlogByLink.getPicUrl2());

                    List<TopicEsInfo> updateList = new ArrayList<>();
                    updateList.add(es);
                    esTemplate.bulkAdd(topicIndex, TopicEsInfo.class.getTypeName(), updateList);

                }
            }
        }
        return String.format("fn_topic(%s)", JSON.toJSONString(object));
    }

    private String getNavTxt(String bodyText) {
        String navTxt = bodyText.replace(" ", "").replace("\r", "").replace("\n", "");
        if (navTxt.length() > 200) {
            navTxt = navTxt.substring(0, 200);
        }
        return navTxt;
    }

    @RequestMapping("update")
    public String update(@RequestBody UpdateTopicDTO updateTopicDTO) throws IOException {
        if (null != updateTopicDTO.getToken()) {
            String _sysToken = "GuoXiongfei";
            //计算token
            //今天的日期
            SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
            if (updateTopicDTO.getToken().equals(_sysToken + "_" + format.format(new Date()))) {
                //Token校验正确
                System.out.print("Token校验正确，正在更新文档");
                String script = "ctx._source.title = '0';ctx._source.click = 100";
                String indexName = EsTemplate.topicIndex;
                String type = TopicEsInfo.class.getTypeName();
                switch (updateTopicDTO.type) {
                    default:
                        break;
                    case "title":
                        script = String.format("ctx._source.title = '%s'", updateTopicDTO.data);
                        esTemplate.updateDocByScript(indexName, type, updateTopicDTO.docId, script);
                        break;
                    case "body":
                        script = String.format("ctx._source.bodyText = '%s'", updateTopicDTO.data);
                        esTemplate.updateDocByScript(indexName, type, updateTopicDTO.docId, script);
                        break;
                }
                HashMap<String, Object> result = new HashMap<>();
                result.put("success", true);
                return JSON.toJSONString(result);
            }
        }
        return JSON.toJSONString(new Object());
    }
}
